import { 
  AssetInfo, 
  InvestmentConfig, 
  BuyPoint, 
  InvestmentPlan, 
  EfficiencyMetrics,
  StrategyType,
  RiskAnalysis
} from '../types/investment';

export class InvestmentCalculator {
  
  /**
   * 生成投资计划
   */
  static generateInvestmentPlan(assetInfo: AssetInfo, config: InvestmentConfig): InvestmentPlan {
    const buyPoints = this.calculateBuyPoints(assetInfo, config);
    const totalInvestment = buyPoints.reduce((sum, point) => sum + point.buyAmount, 0);
    const expectedShares = buyPoints.reduce((sum, point) => sum + point.shares, 0);
    const averagePrice = totalInvestment / expectedShares;
    
    return {
      config,
      buyPoints,
      totalInvestment,
      expectedShares,
      averagePrice,
      riskAnalysis: this.calculateRiskAnalysis(assetInfo, buyPoints, averagePrice)
    };
  }

  /**
   * 计算买入点
   */
  static calculateBuyPoints(assetInfo: AssetInfo, config: InvestmentConfig): BuyPoint[] {
    const { currentPrice, maxDrawdown } = assetInfo;
    const { totalAmount, buyTimes, strategy } = config;
    
    // 基于历史最大回撤计算价格区间
    const minPrice = currentPrice * (1 + maxDrawdown / 100); // maxDrawdown是负数
    const priceStep = (currentPrice - minPrice) / (buyTimes - 1);
    
    const buyPoints: BuyPoint[] = [];
    const weights = this.getStrategyWeights(strategy, buyTimes);
    
    for (let i = 0; i < buyTimes; i++) {
      const targetPrice = currentPrice - (priceStep * i);
      const buyAmount = totalAmount * weights[i];
      const shares = buyAmount / targetPrice;
      const priceDropPercent = ((currentPrice - targetPrice) / currentPrice) * 100;
      
      buyPoints.push({
        order: i + 1,
        targetPrice: Number(targetPrice.toFixed(2)),
        buyAmount: Number(buyAmount.toFixed(2)),
        shares: Number(shares.toFixed(0)),
        priceDropPercent: Number(priceDropPercent.toFixed(1)),
        triggerCondition: this.generateTriggerCondition(targetPrice, currentPrice, i)
      });
    }
    
    return buyPoints;
  }

  /**
   * 获取不同策略的权重分配
   */
  static getStrategyWeights(strategy: StrategyType, buyTimes: number): number[] {
    switch (strategy) {
      case 'equal':
        // 等额投资
        return new Array(buyTimes).fill(1 / buyTimes);
      
      case 'pyramid':
        // 金字塔策略：价格越低买入越多
        const pyramidWeights: number[] = [];
        const totalWeight = (buyTimes * (buyTimes + 1)) / 2;
        for (let i = 0; i < buyTimes; i++) {
          pyramidWeights.push((i + 1) / totalWeight);
        }
        return pyramidWeights;
      
      case 'aggressive':
        // 激进策略：后期大幅加仓
        const aggressiveWeights: number[] = [];
        const base = 0.5;
        const growth = 1.5;
        let aggressiveTotalWeight = 0;
        
        // 先计算总权重
        for (let i = 0; i < buyTimes; i++) {
          aggressiveTotalWeight += Math.pow(growth, i) * base;
        }
        
        // 计算标准化权重
        for (let i = 0; i < buyTimes; i++) {
          aggressiveWeights.push((Math.pow(growth, i) * base) / aggressiveTotalWeight);
        }
        return aggressiveWeights;
      
      default:
        return new Array(buyTimes).fill(1 / buyTimes);
    }
  }

  /**
   * 生成触发条件描述
   */
  static generateTriggerCondition(targetPrice: number, currentPrice: number, index: number): string {
    if (index === 0) {
      return `当前价格 ${currentPrice.toFixed(2)} 时立即买入`;
    }
    
    const dropPercent = ((currentPrice - targetPrice) / currentPrice * 100).toFixed(1);
    return `价格跌至 ${targetPrice.toFixed(2)} (跌幅 ${dropPercent}%) 时买入`;
  }

  /**
   * 计算风险分析
   */
  static calculateRiskAnalysis(assetInfo: AssetInfo, buyPoints: BuyPoint[], averagePrice: number): RiskAnalysis {
    const { currentPrice, maxDrawdown } = assetInfo;
    const worstCasePrice = currentPrice * (1 + maxDrawdown / 100);
    const maxLoss = (averagePrice - worstCasePrice) / averagePrice * 100;
    
    return {
      maxLoss: Number(maxLoss.toFixed(2)),
      breakEvenPrice: Number(averagePrice.toFixed(2)),
      riskLevel: this.getRiskLevelDescription(maxLoss)
    };
  }

  /**
   * 获取风险等级描述
   */
  static getRiskLevelDescription(maxLoss: number): string {
    if (maxLoss < 10) return '低风险';
    if (maxLoss < 20) return '中等风险';
    if (maxLoss < 30) return '较高风险';
    return '高风险';
  }

  /**
   * 获取策略描述
   */
  static getStrategyDescription(strategy: StrategyType): string {
    const descriptions: Record<StrategyType, string> = {
      equal: '等额投资 - 每次买入相同金额，风险分散均匀',
      pyramid: '金字塔策略 - 价格越低买入越多，适合长期投资',
      aggressive: '激进策略 - 大幅下跌时重仓买入，高风险高收益'
    };
    return descriptions[strategy];
  }

  /**
   * 计算投资效率指标
   */
  static calculateEfficiencyMetrics(plan: InvestmentPlan, assetInfo: AssetInfo): EfficiencyMetrics {
    const { buyPoints } = plan;
    const currentPrice = assetInfo.currentPrice;
    
    // 计算如果全部按当前价格买入的对比
    const currentPriceShares = plan.totalInvestment / currentPrice;
    const planShares = plan.expectedShares;
    const shareAdvantage = ((planShares - currentPriceShares) / currentPriceShares * 100);
    
    // 计算成本优势
    const costAdvantage = ((currentPrice - plan.averagePrice) / currentPrice * 100);
    
    return {
      shareAdvantage: Number(shareAdvantage.toFixed(2)),
      costAdvantage: Number(costAdvantage.toFixed(2)),
      executionComplexity: buyPoints.length > 5 ? '复杂' : buyPoints.length > 3 ? '中等' : '简单'
    };
  }
}